package com.giacom.docx4j.xml.util;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.hibernate.metamodel.relational.Schema;

import com.giacom.document.Documento;

/**
 * Classe utilitaria para tratamento de XML
 * @author sandro.giacomozzi
 *
 */
public class JaxbUtil {
	
	
	/**
	 * Converte um object Jaxb em arquivo XML
	 * @param fileName
	 * @param jaxbElement
	 * @throws Exception
	 */
	public static void geraXML(String fileName, Object jaxbElement) throws Exception{
		JAXBContext context = JAXBContext.newInstance("com.giacom.document");
		Marshaller marshaller = context.createMarshaller();
		//marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "Documento.xsd");
		marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "Documento.xsd");
		
		
		File f = new File(fileName);
		marshaller.marshal(jaxbElement, f);
		
		System.out.println("Arquivo gerado: " + f.getAbsoluteFile());
		
	}
	
	/**
	 * Abre o arquivo XML e realiza e converte para Documento
	 * @param fileName 
	 * @return Documento
	 */
	public static Documento carregaDocumento(String fileName) throws Exception{
		try {
			JAXBContext jc = JAXBContext.newInstance(Documento.class);
			
			Unmarshaller unmarshaller = jc.createUnmarshaller();
	        File xml = new File(fileName);
	        Documento d = (Documento) unmarshaller.unmarshal(xml);
	        
	        return d;
			
		} catch (JAXBException e) {
			throw new Exception("Erro ao carregar XML: " + fileName, e);
		}

	}

}
